<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>增加商品</span>
        </div>
      </template>
      <div style="max-width: 800px">
        <el-form :model="item" :rules="rules" ref="itemAdd" label-width="120px">
          <el-form-item label="商品名字" prop="itemName">
            <el-input v-model="item.itemName" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="item.price" />
          </el-form-item>
          <el-form-item label="所属分类" prop="cateId">
            <el-select v-model="item.cateId" placeholder="请选择商品分类">
              <el-option v-for="cate in cates" :key="cate.id" :label="cate.cateName" :value="cate.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="上下架">
            <el-switch v-model="item.onsale" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input v-model="item.desc" type="textarea" />
          </el-form-item>
          <el-form-item label="商品封面">
            <el-upload class="upload-demo" action="/api/upload" name="file" accept="image/*" :on-success="uploadSuccess"
              :before-upload="beforeUpload">
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png/gif，且体积不能超出1m
                </div>
              </template>
            </el-upload>
            <img :src="item.thumb" width="100" alt="">
          </el-form-item>
          <el-form-item label="商品详情">
            <div style="border:1px solid #999">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                mode="default"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="item.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="onCreated"
            />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { fetchCateLists } from '@a/cateLists'
import { fetchItemDetail, updateItem } from '@a/itemLists'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
  name: 'ItemUpate',
  data () {
    return {
      rules: {
        itemName: [
          {
            required: true,
            message: '该字段必填'
          }
        ],
        price: [
          {
            required: true,
            type: 'number',
            message: '该字段必填'
          }
        ],
        cateId: [
          {
            validator: (rule, value, cb) => {
              if (value === -1) {
                cb(new Error('请选择一个分类'))
              } else {
                cb()
              }
            }
          }
        ]
      },
      item: {
        itemName: '',
        price: 0,
        onsale: 1,
        desc: '',
        thumb: '',
        content: '',
        cateId: -1
      },
      // 所有分类
      cates: [],
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入商品详情',
        MENU_CONF: {
          // 定义上传图片配置
          uploadImage: {
            // 后端上传接口地址
            server: '/api/upload',
            customInsert (res, insertFn) { // JS 语法
              // res 即服务端的返回结果
              console.log(res)
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.url)
            }
          }
        }
      }

    }
  },
  methods: {
    fetchItemDetail () {
      fetchItemDetail({
        id: this.$route.query.id
      }).then(res => {
        if (res.data.code === 200) {
          this.item = res.data.data
        }
      })
    },
    onCreated (editor) {
      // 初始化富文本
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    beforeUpload (file) {
      // 限制上传文件的体积  byte
      if (file.size > (1024 * 1024)) {
        alert('体积超出1m')
        return false
      } else {
        return true
      }
    },
    uploadSuccess (res) {
      // 上传成功的回调
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '上传成功'
        })
        this.item.thumb = res.data.url
      }
    },
    onSubmit () {
      // 判断是否验证通过
      this.$refs.itemAdd.validate(valid => {
        if (valid) {
          updateItem(this.item).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration: 1500,
                onClose: () => {
                  // 增加成功
                  this.$router.replace('/itemLists')
                }
              })
            }
          })
        } else {
          alert('验证不通过')
        }
      })
    },
    fetchCateLists () {
      fetchCateLists().then(res => {
        if (res.data.code === 200) {
          this.cates = res.data.data.lists
        }
      })
    }
  },
  created () {
    this.fetchCateLists()
    this.fetchItemDetail()
  },
  components: {
    Editor,
    Toolbar
  }
}

</script>

<style lang="scss" scoped>

</style>
